import React, {useRef, useState} from "react";
import {ButtonGroup, FileButton, LinkButton, Panel, DataList, FormField, Form, ComboBox, TextBox} from "rc-easyui";
import {tfield, tparam} from "@kordar-lib/i18n";
import {fetchConfigOptions} from "@kordar/easyui-tpl";
import {datasetUpload} from "../../../service/bucket_service";
import {max} from "lodash-es";

const FormPanel = ({pageConfig, fetchConfig, dataset}) => {

    const [formData, loadFormData] = useState({create_type: 'file', scan: ''})
    const form = useRef(null)

    const dataListRef = useRef(null)

    const rules = {
        name: {required: true},
        create_type: {required: true},
    }

    const handleChange = (name, value) => {
        loadFormData({...formData, [name]: value})
    };

    const [files, setFiles] = React.useState([]);

    const handleSelect = (items) => {
        items.forEach(file => {
            file.url = window.URL.createObjectURL(file);
        })
        setFiles([...files, ...items])
    }

    const handleRemoveFile = (file) => {
        const items = files.filter(f => f !== file);
        setFiles([...items]);
    }

    const handleClear = () => {
        setFiles([]);
    }

    const onSubmit = () => {

        if (formData.create_type === "file") {
            uploadByFiles()
        }




    }

    function uploadChunkData(domNode, key, file, chunkArr, index, path, filename) {
        const target = domNode.querySelector(`.progress-bar[data-index="${key}"]`);
        const loadingTarget = domNode.querySelector(`.size[data-index="${key}"]`);

        let blob = chunkArr[index]
        let body = new FormData();
        body.append('file', blob, index + "-" + file.name);
        body.append('bucket_id', dataset.bucket_id);
        body.append('dataset_id', dataset.id);
        body.append('type', "chunk");
        body.append('path', path);
        body.append('filename', filename);
        body.append('position', file.finishedByte);

        console.log(blob.size, file.finishedByte, "xxxxxxxxxxxxx")

        datasetUpload(body, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: (progressEvent) => {
                const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total * (blob.size / file.size) + file.progress) ;
                target.style.width = `${percent}%`;
                loadingTarget.innerHTML = `${percent}% <span class="panel-loading" ></span>`;
            }
        }).then(({data, code, message}) => {
            if (code === 200) {
                file.progress += blob.size / file.size * 100
                file.finishedByte += blob.size
                console.log('progress', file.progress, blob.size, file.size);
                console.log('finished', file.finishedByte);

                if (index === chunkArr.length-1) {
                    file.finished = true;
                    loadingTarget.innerHTML = "100% <span class=\"iconfont icon-ok color-dark-green\"></span>";
                } else {
                    uploadChunkData(domNode, key, file, chunkArr, index+1, data.path, data.filename);
                }

            } else {
                target.style.background = 'lightcoral';
            }
        })
    }

    const uploadChunk = (file, index, domNode) => {
        file.progress = 0
        file.finishedByte = 0
        const chunkArr = createChunk(file, 100 * 1024 *1024);
        uploadChunkData(domNode, index, file, chunkArr, 0, "", "", 0);
    }

    const createChunk = (file, chunkSize) => {
      const result = []
        for (let i = 0; i < file.size; i += chunkSize) {
            result.push(file.slice(i, i + chunkSize));
        }
        return result;
    }

    const uploadByFiles = () => {
        files.forEach((file, index) => {

            if (file.finished) {
                return
            }

            let domNode = dataListRef.current?.innerRef;
            if (domNode) {

                if (file.size >= 10 * 1024 *1024 ) {
                    uploadChunk(file, index, domNode)
                    return;
                }

                let body = new FormData();
                body.append('file', file);
                body.append('bucket_id', dataset.bucket_id);
                body.append('dataset_id', dataset.id);
                body.append('type', "images");

                const target = domNode.querySelector(`.progress-bar[data-index="${index}"]`);
                const loadingTarget = domNode.querySelector(`.size[data-index="${index}"]`);

                datasetUpload(body, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    onUploadProgress: (progressEvent) => {
                        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                        target.style.width = `${percent}%`;
                        loadingTarget.innerHTML = `${percent}% <span class="panel-loading" ></span>`;
                    }
                }).then(({data, code, message}) => {
                    if (code === 200) {
                        file.finished = true;
                        loadingTarget.innerHTML = "100% <span class=\"iconfont icon-ok color-dark-green\"></span>";
                    } else {
                        target.style.background = 'lightcoral';
                    }
                })
            }

        })
    }

    const  renderItem = ({row, rowIndex}) => {
        return (
            <div className="fileitem">
                <div className="progress-bar" data-index={rowIndex}></div>
                {
                    row.type.startsWith("image") ? <img alt="" src={row.url} /> : ""
                }
                <div className="name">{row.name}</div>
                <div className="size">{row.size}</div>
                <div className="size" data-index={rowIndex}></div>
                <LinkButton iconCls="icon-clear" data-index={rowIndex} plain onClick={() => handleRemoveFile(row)} style={{zIndex: 99}}></LinkButton>
            </div>
        )
    }

    return (
        <Form ref={form}
              model={formData}
              labelWidth={120}
              labelAlign="left"
              errorType="tooltip"
              rules={rules}
              style={{minWidth: 800, padding: '20px'}}
              onChange={handleChange}
        >

            <FormField name="create_type" label={tfield(pageConfig, 'label.create_type.label', 'Type') + ":"}>
                <ComboBox data={fetchConfigOptions(fetchConfig, "create-type")} value={formData['create_type']} />
            </FormField>

            {
                formData.create_type === "scan" ? <FormField name="scan" label={tfield(pageConfig, 'label.scan.label', 'Scan') + ":"}>
                    <TextBox multiline placeholder={tfield(pageConfig, 'label.scan.placeholder', '')}
                             value={formData.scan}
                             style={{width: '100%', height: 120, padding: 5}}></TextBox>
                </FormField> : ""
            }

            {
                formData.create_type === "file" ? <FormField label={tfield(pageConfig, 'label.files.label', 'Files') + ":"}>
                    <Panel style={{ width: '100%' }}>
                        <div className="panel-header" style={{ border: 0 }}>
                            <ButtonGroup>
                                <FileButton style={{ width: 110 }}
                                            text="Select Files..."
                                            accept="image/*,.zip"
                                            multiple
                                            onSelect={handleSelect}
                                />
                                <LinkButton style={{ width: 80 }} onClick={handleClear}>Clear</LinkButton>
                            </ButtonGroup>
                        </div>
                        <DataList
                            ref={dataListRef}
                            style={{ minHeight: 100, maxHeight: 500 }}
                            border={false}
                            data={files}
                            renderItem={renderItem}
                        />
                    </Panel>
                </FormField> : ""
            }

            <div className="admin-form-submit">
                <LinkButton style={{width: 80}} onClick={onSubmit}
                            iconCls="icon-save">{tparam(pageConfig, 'submit.text', 'Submit')}</LinkButton>
                <LinkButton style={{width: 80}} onClick={close}
                            iconCls="icon-cancel">{tparam(pageConfig, 'close.text', 'Close')}</LinkButton>
            </div>
        </Form>
    )
}

export default FormPanel
